import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import express from 'express'
import { createServer as createViteServer } from 'vite'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

async function createServer() {
  const app = express()
  
  // 创建 Vite 服务器
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })
  
  app.use(vite.middlewares)
  
  app.use('*', async (req, res) => {
    try {
      const url = req.originalUrl
      
      // 1. 读取 index.html
      let template = fs.readFileSync(
        path.resolve(__dirname, '../index.html'),
        'utf-8'
      )
      
      // 2. 应用 Vite HTML 转换
      template = await vite.transformIndexHtml(url, template)
      
      // 3. 加载服务端入口
      const { render } = await vite.ssrLoadModule('/src/entry-server.ts')
      
      // 4. 渲染应用 HTML
      const [appHtml, preloadLinks, piniaState] = await render(url)
      
      // 5. 注入渲染内容
      const html = template
        .replace('<!--preload-links-->', preloadLinks)
        .replace('<!--app-html-->', appHtml)
        .replace('"<!--pinia-state-->"', JSON.stringify(piniaState))
      
      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      vite.ssrFixStacktrace(e)
      console.error(e)
      res.status(500).end(e.message)
    }
  })
  
  app.listen(3000, () => {
    console.log('Server running at http://localhost:3000')
  })
}

createServer()